﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using IGolovkine.ShoutCastRipper;
using IGolovkine.Core.Diagnostics;

namespace IGolovkine.ShoutCastRipper.Service
{
    public class FileLogWriter : ILogWriter
    {
        private string _pathMask;
        public FileLogWriter(string pathMask)
        {
            _pathMask = pathMask;
        }

        public void WriteLine(string format, params object[] args)
        {
            string message = string.Format(format, args);
            using (StreamWriter writer = this.GetFileStream())
            {
                writer.WriteLine(AppendTimeStamp(message));
            }
        }

        private StreamWriter GetFileStream()
        {
            string filePathFormat = _pathMask.Replace("DateTime", "0");
            string filePath = string.Format(filePathFormat, DateTime.Now);
            if (Directory.Exists(Path.GetDirectoryName(filePath)) == false)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }

            return new StreamWriter(filePath, true);
        }

        public void WriteLine()
        {
            using (StreamWriter writer = this.GetFileStream())
            {
                writer.WriteLine();
            }
        }

        public void WriteLine(string message)
        {
            using (StreamWriter writer = this.GetFileStream())
            {
                writer.WriteLine(AppendTimeStamp(message));
            }
        }

        public void WriteException(string message, Exception ex)
        {
            this.WriteLine(); 
            this.WriteLine("### EXCEPTION ### " + message + Environment.NewLine + ObjectDumper.Format(ex));
            this.WriteLine();
        }

        private static string AppendTimeStamp(string message)
        {
            return string.Format("[{0:HH:mm:ss}] ", DateTime.Now) + message;
        }


        public void WriteDebug(string format, params object[] args)
        {
#if DEBUG
            this.WriteLine("%DEBUG% " + string.Format(format, args));
#endif
        }
    }
}
